#include <iostream>
#include <unistd.h>
#include <time.h>
#include <string>
#include "log.hpp"
#include "Socket.hpp"
#include "Protocal.hpp"



void Usage()
{
    std::cout << "\n\r" << "[Usage]:port" <<"\n" << std::endl; 

}


int main(int argc ,char* argv[])
{
    if(argc != 3)
    {
        Usage();
        return -1;
    }
    srand(time(nullptr));
    Sock sock;
    sock.Socket();
    std::string ip = argv[1];
    std::string port_1 = argv[2];
    std::cout << "port: " << port_1 << std::endl;
    uint16_t port = std::stoi(port_1);
    sock.Connect(ip,port);


    lg(INFO,"connect successful");
    std::string op = "+-*/%";
    int cnt = 1;

    while(true)
    {
        cnt++;

        Requset req;
        req.x_ = rand() % 100 + 1;
        req.y_ = rand() % 100;
        req.op_ = op[rand() % op.size()];
        
        

        std::string con;
        std::string out_stream;

        //序列化
        bool r = req.Serialize(&con);
        if(!r) lg(WARNING,"Serialize failure");
        //std::cout << "con:   " << con << std::endl;
    
        out_stream = Encode(con);
        //std::cout << out_stream << out_stream.size() <<std::endl;
       
        std::cout << "============" <<"  The  " <<cnt <<"  Request  "<<"============"<<std::endl;
        std::cout << "x: "<< req.x_ <<std::endl;
        std::cout << "op: "<< req.op_ <<std::endl;
        std::cout << "y: "<< req.y_ <<std::endl;

        
         
        //写给网络
        write(sock.GetFd(),out_stream.c_str(),out_stream.size());
        //std::cout << "-----write succ "<< req.y_ <<std::endl;
        //sleep(2);
        //读取
        std::string in_stream;
        char inbuffer[1024];
        
        int n = read(sock.GetFd(),&inbuffer,sizeof(inbuffer));   
        //std::cout << "-----read succ "<< req.y_ <<std::endl;     
        if(n > 0)
        {
            inbuffer[n] = 0;
        }

        //std::cout << "-----read succ "<< inbuffer <<std::endl;
        in_stream += inbuffer;
        //std::cout << "-----in_stream "<< in_stream <<std::endl;

        std::string bon; 
        Response resp;
        Decode(in_stream,&bon);

        //std::cout << "bon" << bon <<std:: endl;
        //std::cout << "-----Decode succ "<< req.y_ <<std::endl;

        // 这个bon 是空的
        resp.Deserialize(bon);
        //std::cout << bon << std::endl;
        
        resp.Print();
        sleep(1);

        std::cout << "========================================"<<std::endl;
    }


    return 0;
}